package com.mf.morefun.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.bean.LoginBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.requestbean.RequestLoginBean;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.DateUtils;
import com.zhcx.zhcxlibrary.utils.DeviceUtils;
import com.zhcx.zhcxlibrary.utils.FileUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

public class HeartbeatService extends Service implements Runnable {
    private Thread mThread;
    public int count = 0;
    private SPUtils mSputils;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void run() {
        while (true) {
            try {
                //向服务器发送心跳包
                if (!StringUtils.isEmpty(mSputils.getString(Configuration.USERPHONE)) && !StringUtils.isEmpty(mSputils.getString(Configuration.USERPASSWORD))){
                    initLogin(mSputils.getString(Configuration.USERPHONE), mSputils.getString(Configuration.USERPASSWORD));
                }
                Thread.sleep(1000 * 60 * 60);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void initLogin(String user, String password) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.LOGIN);
        RequestLoginBean bean = new RequestLoginBean();
        bean.setPhone(user);
        bean.setPassword(FileUtils.md5(password));
        params.setBodyContent(JSON.toJSONString(bean));
        params.setCharset("UTF-8");
        params.addHeader("Content-Type", "application/json");
        params.setConnectTimeout(10000);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d(result);
                if (!StringUtils.isEmpty(result)) {
                    MoreFunApplication.loginBean = JSON.parseObject(result, LoginBean.class);
                    if (MoreFunApplication.loginBean.getErrorCode() == 0) {
                        try {
                            if (MoreFunApplication.loginBean.getResult().getEnableEnd().length() == 10){
                                long enableTime = DateUtils.DEFAULT_DATE_FORMAT.parse(MoreFunApplication.loginBean.getResult().getEnableEnd() + " 23:59:59").getTime();
                                long currentTime = System.currentTimeMillis();
                                if (enableTime < currentTime) {
                                    EventBus.getDefault().post("LOGOUT");
                                }
                            }else {
                                long enableTime = DateUtils.DEFAULT_DATE_FORMAT.parse(MoreFunApplication.loginBean.getResult().getEnableEnd()).getTime();
                                long currentTime = System.currentTimeMillis();
                                if (enableTime < currentTime) {
                                    EventBus.getDefault().post("LOGOUT");
                                }
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                            EventBus.getDefault().post("LOGOUT");
                        }
                    } else {
                        EventBus.getDefault().post("LOGOUT");
                    }
                } else {
                    EventBus.getDefault().post("LOGOUT");
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            mSputils = new SPUtils(AppManager.getAppManager().currentActivity());
            mThread = new Thread(this);
            mThread.start();
        }catch (Exception e){
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }
}
